package com.example.contactapp;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

public class SideIndexView extends View {

    private Paint paint;
    private List<String> indexList;
    private OnTouchIndexListener onTouchIndexListener;
    private int currentIndex = -1;

    public SideIndexView(Context context) {
        super(context);
        init();
    }

    public SideIndexView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public SideIndexView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setTextSize(50);
        paint.setAntiAlias(true);
        indexList = new ArrayList<>();
        for (char c = 'a'; c <= 'z'; c++) {
            indexList.add(String.valueOf(c));
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int height = getHeight();
        int width = getWidth();
        int itemHeight = height / indexList.size();

        for (int i = 0; i < indexList.size(); i++) {
            String text = indexList.get(i);
            float x = (width - paint.measureText(text)) / 2;
            float y = (i + 1) * itemHeight - (itemHeight - paint.getFontMetrics().bottom - paint.getFontMetrics().top) / 2;
            if (i == currentIndex) {
                paint.setColor(Color.RED);
            } else {
                paint.setColor(Color.BLACK);
            }
            canvas.drawText(text, x, y, paint);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        float y = event.getY();
        int index = (int) (y / getHeight() * indexList.size());

        if (index >= 0 && index < indexList.size()) {
            if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_MOVE) {
                currentIndex = index;
                if (onTouchIndexListener != null) {
                    onTouchIndexListener.onTouchIndex(indexList.get(index));
                }
                invalidate();
            } else if (action == MotionEvent.ACTION_UP) {
                currentIndex = -1;
                invalidate();
            }
        }
        return true;
    }

    public void setOnTouchIndexListener(OnTouchIndexListener listener) {
        this.onTouchIndexListener = listener;
    }

    public interface OnTouchIndexListener {
        void onTouchIndex(String index);
    }
}